<template>
  <div @click="progressClick" class="progress-bar" ref="progressBar">
    <div class="bar-inner">
      <div class="progress" ref="progress"></div>
      <div class="progress-btn-wrapper" ref="progressBtn">
        <div :class="{ show: alwaysShowBtn }" class="progress-btn"></div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { toCurrentRem } from '@/common/rem'


export default {
  name: 'ProgressBar',
  props: {
    percent: {
      type: Number,
      default: 0
    },
    alwaysShowBtn: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    if (this.percent > 0) {
      this.setProgressOffset(this.percent)
    }
  },
  methods: {
    // 播放进度条点击事件
    progressClick(e) {
      if (!this.disabled) {
        // getBoundingClientRect用于获取某个元素相对于视窗的位置集合。集合中有top, right, bottom, left等属性
        const rect = this.$refs.progressBar.getBoundingClientRect()
        // 计算偏移量 (点击位置 - 当前播放器相对于视窗的left位置)
        const offset = e.pageX - rect.left
        // 计算当前percent （当前进度条长度 / 进度条总长度）
        const curPercent = offset / this.$refs.progressBar.offsetWidth
        // 触发父类percent改变事件改变当前音频时间
        this.$emit('percentChange', curPercent)
      }
    },
    // 根据时间百分比设置进度条偏移量
    setProgressOffset(percent) {
      if (percent >= 0) {
        // 计算偏移量 (百分比 * 进度条总宽度)
        const offset = percent * this.$refs.progressBar.offsetWidth
        // 设置进度条宽度
        this.$refs.progress.style.width = toCurrentRem(offset)
        // 设置播放头偏移量
        this.$refs.progressBtn.style.left = toCurrentRem(
          offset - this.$refs.progressBtn.offsetWidth / 2
        )
      }
    }
  },
  watch: {
    // 监听时间百分比变化设置进度条偏移量
    percent(newPercent) {
      this.setProgressOffset(newPercent)
    }
  }
}
</script>

<style scoped lang="scss">
.progress-bar {
  height: 30px;
  cursor: pointer;

  .bar-inner {
    position: relative;
    top: 14px;
    height: 2px;
    background: var(--progress-bgcolor);

    .progress {
      position: absolute;
      height: 100%;
      background: $theme-color;
    }

    .progress-btn-wrapper {
      position: absolute;
      left: -15px;
      top: -13px;
      width: 30px;
      height: 30px;

      .progress-btn {
        display: none;
        position: relative;
        top: 8px;
        left: 9px;
        box-sizing: border-box;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: $theme-color;

        &.show {
          display: block;
        }
      }
    }
  }

  &:hover {
    .progress-btn {
      display: block !important;
    }
  }
}
</style>
